/**   
 * @Title: MainAction.java 
 * @Package com.foreveross.smsh.core.web 
 * @Description: TODO 
 * @author lixiaodong lixiaodong@foreveross.com  
 * @date 2016年3月7日 下午4:00:59 
 * @version V1.0   
 */
package com.foreveross.smsh.core.web;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.commons.lang3.StringUtils;
import org.hibernate.SQLQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.foreveross.smsh.core.pojo.TreeNode;
import com.foreveross.smsh.models.menu.pojo.Menu;
import com.foreveross.smsh.models.menu.service.MenuService;

@Controller
public class MainAction extends BaseAction{

	@Autowired
	MenuService menuService;
	@RequestMapping(value="/main",method=RequestMethod.GET)
	public String main(){
		//getRootMenu(roleId);
		this.attr("menus", getMenu());
		return "models/main";
	}
	
	public List<Menu> getMenu(){
		List<Menu> menus =menuService.get("type", 0);
		return menus;
	}
	@RequestMapping(value="/menu/getChildren",method=RequestMethod.POST)
	@ResponseBody
	public void getChildren(String parentId) {
		List<TreeNode> treeNodes = new ArrayList<TreeNode>();
		List<Menu> menus =menuService.get("parentId",parentId);
		for (Menu menu : menus) {
			treeNodes.add(convert(menu));
		}
		this.printJson(treeNodes);
	}
	/**
	 * 将organ对象转换为treenode对象
	 * @param organ
	 * @return
	 */
	private TreeNode convert(Menu menu) {
		TreeNode node=new TreeNode();
		node.setId(menu.getId());
		node.setText(menu.getName());
		if(menu.getType()==0){
			node.setState(TreeNode.STATE_CLOSED);
		}else{
			node.setState(TreeNode.STATE_OPEN);
		}
		node.getAttributes().put("url", menu.getUrl());
		node.getAttributes().put("parentId", menu.getParentId());
		node.getAttributes().put("type", menu.getType());
		return node;
	}
	
	public List<Menu> getRootMenu(String roleId){
		Map<String, Object> params =new HashMap<String, Object>();
		params.put("roleId", roleId);
	  SQLQuery query = menuService.getSQLQuery("select m.* from tbl_menu m ,tbl_role_menu rm where  m.id = rm.menu_id and  rm.role_id =:roleId ", params );
	  query.addEntity(Menu.class);
	 @SuppressWarnings("unchecked")
	List<Menu> menus =  query.list();
	 Set<Menu> topMens = new HashSet<Menu>();
	 for (Menu menu : menus) {
		 topMens.add(getTopMenu(menu.getId()));
	 }
		return new ArrayList<Menu>(topMens);
	}
	
	public Menu getTopMenu(String id){
		Menu menu =menuService.get(id);
		if(StringUtils.isNotBlank(menu.getParentId())){
			getTopMenu(menu.getParentId());
		}
		return menu;
	}
	
}
